package com.magicode.screen.util;

import java.net.URLDecoder;

import com.magicode.screen.R;
import com.magicode.screen.activity.MainActivity;
import com.magicode.screen.activity.ThirdPartyLoginActivity;
import com.magicode.screen.alipay.AliPayActivity;

import com.magicode.screen.react.activity.MainTabReactActivity;


import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
//import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.widget.ZoomButtonsController;

import com.magicode.screen.react.activity.PayFailReactActivity;
import com.magicode.screen.react.activity.PaySuccessReactActivity;
import com.magicode.screen.wxapi.WXPayActivity;



/**
 * 界面帮助类
 * 
 * @author FireAnt（http://my.oschina.net/LittleDY）
 * @version 创建时间：2014年10月10日 下午3:33:36
 * 
 */
public class UIHelper {

    /** 全局web样式 */
    // 链接样式文件，代码块高亮的处理
    public final static String linkCss = "<script type=\"text/javascript\" src=\"file:///android_asset/shCore.js\"></script>"
            + "<script type=\"text/javascript\" src=\"file:///android_asset/brush.js\"></script>"
            + "<script type=\"text/javascript\" src=\"file:///android_asset/client.js\"></script>"
            + "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/shThemeDefault.css\">"
            + "<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/shCore.css\">"
            + "<script type=\"text/javascript\">SyntaxHighlighter.all();</script>"
            + "<script type=\"text/javascript\">function showImagePreview(var url){window.location.url= url;}</script>";
    public final static String WEB_STYLE = linkCss
            + "<style>* {font-size:16px;line-height:20px;} p {color:#333;} a {color:#3E62A6;} img {max-width:310px;} "
            + "img.alignleft {float:left;max-width:120px;margin:0 10px 5px 0;border:1px solid #ccc;background:#fff;padding:2px;} "
            + "pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;overflow: auto;} "
            + "a.tag {font-size:15px;text-decoration:none;background-color:#cfc;color:#060;border-bottom:1px solid #B1D3EB;border-right:1px solid #B1D3EB;color:#3E6D8E;margin:2px 2px 2px 0;padding:2px 4px;white-space:nowrap;position:relative}</style>";

    public static final String WEB_LOAD_IMAGES = "<script type=\"text/javascript\"> var allImgUrls = getAllImgSrc(document.body.innerHTML);</script>";

    private static final String SHOWIMAGE = "ima-api:action=showImage&data=";

    /**
     *调用第三方登录
     * 
     * @param context
     */
    public static void
    showThirdPartyLoginActivity(Context context,String type) {
        Intent intent = new Intent();
        intent.setClass(context,ThirdPartyLoginActivity.class);
        ThirdPartyLoginActivity.type=type;
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
    }
    /**
     * 显示 支付宝支付
     *
     * @param context
     */
    public static void showAliPayActivity(Context context,String ruleId) {
        Intent intent = new Intent(context, AliPayActivity.class);
        intent.putExtra("ruleId",ruleId);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK );
        context.startActivity(intent);
    }
    /**
     * 显示 微信支付
     *
     * @param context
     */
    public static void showWXPayActivity(Context context,String ruleId) {
        Intent intent = new Intent(context, WXPayActivity.class);
        intent.putExtra("ruleId",ruleId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    /**
     * 显示 MainTab
     *
     * @param context
     */
    public static void showMainTabActivity(Context context) {
        Intent intent = new Intent(context,MainTabReactActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    /**
     * 显示 Main
     *
     * @param context
     */
    public static void showMainActivity(Context context) {
        Intent intent = new Intent(context,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    /**
     * 显示 支付 成功 页面react
     *
     * @param context
     */
    public static void showPaySuccessReactActivity(Context context) {
        Intent intent = new Intent(context, PaySuccessReactActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    /**
     * 显示 支付 失败 页面react
     *
     * @param context
     */
    public static void showPayFailReactActivity(Context context) {
        Intent intent = new Intent(context, PayFailReactActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(intent);
    }
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    public static void initWebView(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setDefaultFontSize(15);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        int sysVersion = Build.VERSION.SDK_INT;
        if (sysVersion >= 11) {
            settings.setDisplayZoomControls(false);
        } else {
            ZoomButtonsController zbc = new ZoomButtonsController(webView);
            zbc.getZoomControls().setVisibility(View.GONE);
        }
        webView.setWebViewClient(UIHelper.getWebViewClient());
    }

    /**
     * 获取webviewClient对象
     * 
     * @return
     */
    public static WebViewClient getWebViewClient() {

        return new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                showUrlRedirect(view.getContext(), url);
                return true;
            }
        };
    }


    /**
     * url跳转
     * 
     * @param context
     * @param url
     */
    public static void showUrlRedirect(Context context, String url) {
        if (url == null)
            return;
       
        if (url.startsWith(SHOWIMAGE)) {
            String realUrl = url.substring(SHOWIMAGE.length());
            try {
                JSONObject json = new JSONObject(realUrl);
                int idx = json.optInt("index");
                String[] urls = json.getString("urls").split(",");
   //             showImagePreview(context, idx, urls);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        URLsUtils urls = URLsUtils.parseURL(url);
        if (urls != null) {
            showLinkRedirect(context, urls.getObjType(), urls.getObjId(),
                    urls.getObjKey());
        } else {
            openBrowser(context, url);
        }
    }

    public static void showLinkRedirect(Context context, int objType,
            String objId, String objKey) {
        switch (objType) {
        case URLsUtils.URL_OBJ_TYPE_NEWS:
     //       showNewsDetail(context, objId, -1);
            break;
        case URLsUtils.URL_OBJ_TYPE_ZONE:
            showUserCenter(context, (String)objId, objKey);
            break;
        case URLsUtils.URL_OBJ_TYPE_OTHER:
            openBrowser(context, objKey);
            break;
        case URLsUtils.URL_OBJ_TYPE_TEAM:
            openSysBrowser(context, objKey);
            break;
        case URLsUtils.URL_OBJ_TYPE_GIT:
            openSysBrowser(context, objKey);
            break;
        }
    }

    /**
     * 打开内置浏览器
     *
     * @param context
     * @param url
     */
    public static void openBrowser(Context context, String url) {

        if (StringUtils.isImgUrl(url)) {
//            ImagePreviewActivity.showImagePrivew(context, 0,
//                    new String[] { url });
            return;
        }

        if (url.startsWith("http://www.oschina.net/tweet-topic/")) {
            Bundle bundle = new Bundle();
            int i = url.lastIndexOf("/");
            if (i != -1) {
                bundle.putString("topic",
                        URLDecoder.decode(url.substring(i + 1)));
            }
//            UIHelper.showSimpleBack(context, SimpleBackPage.TWEET_TOPIC_LIST,
//                    bundle);
            return;
        }
        try {
            // 启用外部浏览器
            // Uri uri = Uri.parse(url);
            // Intent it = new Intent(Intent.ACTION_VIEW, uri);
            // context.startActivity(it);
            Bundle bundle = new Bundle();
//            bundle.putString(BrowserFragment.BROWSER_KEY, url);
//            showSimpleBack(context, SimpleBackPage.BROWSER, bundle);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "无法浏览此网页", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 打开系统中的浏览器
     * 
     * @param context
     * @param url
     */
    public static void openSysBrowser(Context context, String url) {
        try {
            Uri uri = Uri.parse(url);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
            ((Activity) context).overridePendingTransition(R.anim.anim_right_get_into, R.anim.anim_left_sign_out);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "无法浏览此网页", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 组合动态的回复文本
     * 
     * @param name
     * @param body
     * @return
     */
    public static SpannableStringBuilder parseActiveReply(String name,
            String body) {
        Spanned span = Html.fromHtml(body.trim());
        SpannableStringBuilder sp = new SpannableStringBuilder(name + "：");
        sp.append(span);
        // 设置用户名字体加粗、高亮
        // sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0,
        // name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(new ForegroundColorSpan(Color.parseColor("#576B95")), 0,
                name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return sp;
    }

    /**
     * 显示用户中心页面
     * 
     * @param context
     * @param hisuid
     * @param hisname
     */
    public static void showUserCenter(Context context, String hisuid, String hisname) {
        if (hisuid == null && hisname.equalsIgnoreCase("匿名")) {
            Toast.makeText(context, "提醒你，该用户为非会员", Toast.LENGTH_LONG).show();
            return;
        }
        Bundle args = new Bundle();
        args.putString("his_id", hisuid);
        args.putString("his_name", hisname);
//        showSimpleBack(context, SimpleBackPage.USER_CENTER, args);
    }


    /**
     * 显示用户头像大图
     * 
     * @param context
     * @param avatarUrl
     */
    @Deprecated
    public static void showUserAvatar(Context context, String avatarUrl) {
        if (StringUtils.isEmpty(avatarUrl)) {
            return;
        }
        //String url = AvatarView.getLargeAvatar(avatarUrl);
        String url = avatarUrl;
   //     ImagePreviewActivity.showImagePrivew(context, 0, new String[] { url });
    }

    /**
     * 获得服务器域名
     * 返回格式: http://app.media-plus.cn/%s
     * @param context
     * @return
     */
    public static String getServerDomain(Context context){
        String result = null;
        result = getServerUrl(context);
        result += "%s";
        return result;
    }

    /**
     * 获得服务器主机名,即不带协议的域名
     * 返回格式: app.media-plus.cn
     * @param context
     * @return
     */
    public static String getServerHost(Context context){
        String result = null;
        result = getServerUrl(context);
//        截取前面的https:// 截取后面 /
        result = result.substring(result.indexOf("://")+3, result.length()-1);

        return result;
    }
    /**
     * 获得服务器URL
     * 返回格式: http://app.media-plus.cn/
     * @param context
     * @return
     */
    public static String getServerUrl(Context context){
        String result = null;
        ApplicationInfo ai  = null;
        try {
            ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        result = ai.metaData.getString("server_url");
        return result;
    }
    /**
     * 获得URL的salt
     * 返回格式: http://app.media-plus.cn/
     * @param context
     * @return
     */
    public static String getUrlSalt(Context context){
        String result = null;
        ApplicationInfo ai  = null;
        try {
            ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        result = ai.metaData.getString("url_salt");
        return result;
    }
}
